// 首先引入axios和上一步封装的cookie方法
import router from "@/router";
import { deleteUserInfo, getToken } from "@/store/modules/user/utils";
import { getTimeZone } from "@/utils/utils";
import { Message } from "@arco-design/web-vue";
import axios, { AxiosInstance } from "axios";
let rootUrl = (globalThis as any)["BASE_URL"];
rootUrl || import.meta.env.VITE_BASEURL;

export const getBaseUrl = () => {
  return rootUrl || import.meta.env.VITE_BASEURL;
};
export const BASE_URL = rootUrl || import.meta.env.VITE_BASEURL;

export class Interceptors {
  instance: AxiosInstance;

  constructor() {
    this.instance = axios.create({
      baseURL: getBaseUrl(),
      timeout: 20000
    });
    this.init();
  }

  // 初始化拦截器
  init() {
    // 请求接口拦截器
    this.instance.interceptors.request.use(
      (config: any) => {
        const token = getToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
          config.headers.timeZone = getTimeZone();
        } else {
          if (config.url === "/login") return config;
          router.push("/login");
          throw new Error("NO_TOKEN");
        }
        return config;
      },
      (err) => {
        // console.error(err);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        const res = response.data;
        if (response.config.method !== "get") {
          if (res.code === 200) {
            Message.info(res.msg);
          } else if (res.code === 500) {
            Message.error(res.msg);
          }
        }
        /* 没有登录 */
        if (res.code === 401) {
          deleteUserInfo();
          Message.warning(res.msg);
          window.location.href = "/";
          return Promise.resolve(res);
        }
        if (res.code === 500) {
          /* 处理参数错误 */
          Message.warning(res.msg);
          // setHttpWarning("请求错误", report);
          return res;
        }
        if (res.code !== 200) {
          /* 成功返回 */
          return res.msg;
        }
        if (!response.status.toString().startsWith("2") || res.code === -1) {
          // 如果状态码不是2开头或者接口code返回-1 则是返回错误信息
        } else {
          return res;
        }
      },
      (error) => {
        if (error.message === "Network Error") {
          return;
        }

        let code = -110;
        if (error && error.response && error.response.status) {
          code = error.response.status;
          // 登录过期
          if (code === 401 || code === -3) {
            deleteUserInfo();
            window.location.href = "/";
          }
        }

        if (error.toString().includes("NO_TOKEN")) return;
        Message.warning(`error:${error}`);
        const err = { errCode: -110, errMsg: error.message || "Error" };

        return Promise.resolve(err);
      }
    );
  }

  // 返回一下
  getInterceptors() {
    return this.instance;
  }
}
